package com.itheima.web;

import com.itheima.bean.ShoppingCart;
import com.itheima.common.R;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 获取购物车的清单
     * @return
     */
    @GetMapping("/list")
    public R findAll(){
        List<ShoppingCart> list = shoppingCartService.findAll();
        return R.success(list);
    }

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){
        try {
            ShoppingCart cart = shoppingCartService.add(shoppingCart);
            return R.success(cart);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("添加购物车失败!");
        }
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(){
        int row = shoppingCartService.delete();
        if (row>0){
           return R.success("清空购物车成功!");
        }
        return R.error("清空购物车失败!");
    }

    /**
     * 删除购物车
     * @param map
     * @return
     */
    @PostMapping("/sub")
    public R delete(@RequestBody Map<String,Long> map){
        ShoppingCart shoppingCart = shoppingCartService.delete(map);
        if (shoppingCart!=null) {
            return R.success(shoppingCart);
        }
        return R.success("删除成功");
    }
}
